﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using Model;

namespace TanHungLong
{
    public partial class FrmPhieuNhap : DevExpress.XtraEditors.XtraForm
    {
        #region variant
        private FormStatus formStatus = FormStatus.View;
        private bool allowCloseForm = true;
        private GiaBOCollection giaBOCollection = null;
        private NhomHangBOCollection nhomHangBOCollection = null;
        private PhieuNhapBOCollection PhieuNhapBOCollection = null;
        private PhieuNhapChiTietBOCollection PhieuNhapChiTietBOCollection = PhieuNhapChiTietBOCollection.NewPhieuNhapChiTietBOCollection();
        private PhieuNhapBO PhieuNhapBO = PhieuNhapBO.NewRootPhieuNhapBO();

        private string COLUMN_FIRST_MatHang = "Ten";
        private string COLUMN_SECOND_MatHang = "SoThuTu";

        private string COLUMN_FIRST_PhieuNhapChiTiet = "Ten";
        private string COLUMN_SECOND_PhieuNhapChiTiet = "HeSo";
        #endregion variant

        //=====================================
        #region form
        public FrmPhieuNhap()
        {
            InitializeComponent();
            this.KeyPreview = true;

            this.Load += new EventHandler(FrmPhieuNhap_Load);
            this.Shown += new EventHandler(FrmPhieuNhap_Shown);
            this.FormClosing += new FormClosingEventHandler(FrmPhieuNhap_FormClosing);
            this.grdViewPhieuNhapChiTiet.KeyDown += new KeyEventHandler(this.FrmHoadonnhap_KeyDown);
            this.txtTimkiem.KeyDown += new KeyEventHandler(this.txtTimkiem_KeyDown);
            this.grdViewMatHang.KeyDown += new KeyEventHandler(this.grdViewMatHang_KeyDown);

            this.btnAdd.Click += new EventHandler(btnAdd_Click);
            this.btnXoa.Click += new EventHandler(btnDelete_Click);
            this.btnRefresh.Click += new EventHandler(btnRefresh_Click);
            this.btnSave.Click += new EventHandler(btnSave_Click);
            this.btnCancel.Click += new EventHandler(btnCancel_Click);
            this.btnClose.Click += new EventHandler(btnClose_Click);
            this.btnRefreshMatHang.Click += new EventHandler(btnRefreshMatHang_Click);

            this.btnNhapKho.Click += new EventHandler(toolStripMenuItemNhapKho_Click);
            this.btnDelPhieuNhap.Click += new EventHandler(btnDelete_Click);

            this.grdViewMatHang.DoubleClick += new System.EventHandler(this.grdViewMatHang_DoubleClick);
            this.gridViewPhieuNhap.RowCellClick += new RowCellClickEventHandler(this.gridViewPhieuNhap_RowCellClick);

            this.grdViewMatHang.RowCellStyle += new RowCellStyleEventHandler(grdView_RowCellStyle);
            this.grdViewPhieuNhapChiTiet.RowCellStyle += new RowCellStyleEventHandler(grdView_RowCellStyle);

            this.grdViewMatHang.ShowingEditor += new CancelEventHandler(grdView_ShowingEditor);
            this.grdViewPhieuNhapChiTiet.ShowingEditor += new CancelEventHandler(grdView_ShowingEditor);
            this.lookUpEditNhaCungCap.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(lookUpEditKhachHang_ButtonClick);
            this.lookUpMaKhachHang.EditValueChanged += new EventHandler(lookUpMaKhachHang_EditValueChanged);
        }

        void lookUpMaKhachHang_EditValueChanged(object sender, EventArgs e)
        {
            lookUpEditNhaCungCap.EditValue = lookUpMaKhachHang.EditValue;
        }

        private void FrmPhieuNhap_Shown(object sender, EventArgs e)
        {
            this.lookUpEditNhaCungCap.Focus();
        }

        private void FrmPhieuNhap_Load(object sender, EventArgs e)
        {

            dtNgayLapHoaDon.DateTime = Session.NgayHeThong;

            Utility.InitControl(this.reLookUpMatHangID);
            Utility.InitControl(this.reLookUpDonViTinhID);

            Utility.InitControl(this.reLookUpMatHang);
            Utility.InitControl(this.reLookUpDonViTinh);
            Utility.InitControl(this.reLookUpDMKhoID);
            Utility.InitControl(this.reLookUpNhaCungCapID);

            this.grdViewMatHang.FocusedRowChanged += new FocusedRowChangedEventHandler(grdViewMatHang_FocusedRowChanged);
            this.grdView.FocusedRowChanged += new FocusedRowChangedEventHandler(grdView_FocusedRowChanged);
            this.txtTimkiem.EditValueChanged += new System.EventHandler(this.txtTimkiem_EditValueChanged);

            this.spinEditPhucVu.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditGiamGia.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditChietKhau.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditVAT.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditTienPhatSinh.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.grdViewPhieuNhapChiTiet.CellValueChanged += new CellValueChangedEventHandler(this.grdViewPhieuNhapChiTiet_CellValueChanged);

            RefreshData();
        }

        private void FrmPhieuNhap_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.allowCloseForm == false)
                e.Cancel = true;
        }

        private void FrmHoadonnhap_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyData == Keys.Delete)
            {
                int _idMatHang = StaticUtil.GetInt(this.grdViewPhieuNhapChiTiet.GetFocusedRowCellValue("MatHangID"), -1);
                int _idDonViTinh = StaticUtil.GetInt(this.grdViewPhieuNhapChiTiet.GetFocusedRowCellValue("DonViTinhID"), -1);
                if ((_idMatHang >= 0) & (_idDonViTinh >= 0))
                {
                    DeleteMatHang(_idMatHang, _idDonViTinh);
                }
                else
                {
                    MessageBox.Show("Bạn chưa chọn Vật tư để xóa! Vui lòng chọn lại", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.grdViewPhieuNhapChiTiet.Focus();
                }
            }

            if (e.KeyCode == Keys.N && Control.ModifierKeys == Keys.Control)
                AddNew();
            if ((e.KeyCode == Keys.Q && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F10))
                this.Close();
            if ((e.KeyCode == Keys.R && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F5))
                RefreshData();
            if ((e.KeyCode == Keys.S && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F6))
                Save();
            if ((e.KeyCode == Keys.T && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F2))
                toolStripMenuItemNhapKho_Click(null, null);
            if ((e.KeyCode == Keys.Delete && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F8))
                btnDelete_Click(null, null);
        }
        #endregion form

        //=====================================
        #region control

        private void txtTimkiem_EditValueChanged(object sender, EventArgs e)
        {
            FilterMatHangByName(txtTimkiem.Text.Trim());
        }


        private void spinEditTienPhatSinh_ValueChanged(object sender, EventArgs e)
        {
            TinhTien();
        }


        void lookUpEditKhachHang_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {
                FrmNewKhachHang.daluu = 0;
                FrmNewKhachHang frNewKH = new FrmNewKhachHang();
                frNewKH.ShowDialog();
                if (FrmNewKhachHang.daluu == 1)
                {
                    KhachHangBOCollection nn = KhachHangBOCollection.GetKhachHangBOCollection();
                    bdSourceNhaCungCap.DataSource = nn.Clone();
                    lookUpEditNhaCungCap.EditValue = lookUpMaKhachHang.EditValue = StaticUtil.GetInt(FrmNewKhachHang.KhachHangBO.KhachHangID, -1);
                    FrmNewKhachHang.daluu = 0;
                }
            }
            else
                if (e.Button.Index == 2)
                    lookUpEditNhaCungCap.EditValue = null;
        }
        #endregion control

        //=====================================
        #region button
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void btnRefreshMatHang_Click(object sender, EventArgs e)
        {
            FilterMatHangByName("");
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddNew();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            Edit();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Cancel();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int _PhieuNhapID = StaticUtil.GetInt(this.PhieuNhapBO.PhieuNhapID, -1);
            if (_PhieuNhapID != -1)
            {
                if (MessageBox.Show("Bạn muốn xóa Phiếu yêu cầu này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Model.PhieuNhapBO.DeletePhieuNhapBO(_PhieuNhapID);
                    for (int k = 0; k < PhieuNhapChiTietBOCollection.Count; k++)
                    {
                        PhieuNhapChiTietBO.DeletePhieuNhapChiTietBO((int)PhieuNhapChiTietBOCollection[k].PhieuNhapChiTietID);
                    }
                    RefreshData();
                    btnAdd_Click(e, e);
                }
            }
            else
            {
                MessageBox.Show("Chưa chọn Phiếu yêu cầu để xóa! ", "Thông báo", MessageBoxButtons.OK);
            }
        }
        #endregion button

        //=====================================
        #region grid
        private void grdViewMatHang_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            //FilterMatHang();
        }

        private void grdView_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            FilterMatHang();
        }

        private void grdView_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView grdView = (GridView)sender;

            bool del = StaticUtil.GetBool(grdView.GetFocusedRowCellValue("DELE"));
            string fieldName = grdView.FocusedColumn.FieldName;

            if (del && fieldName != "DELE")
                e.Cancel = true;
            else
                if (fieldName == "DELE" && grdView.FocusedRowHandle == GridControl.NewItemRowHandle)
                    e.Cancel = true;
        }

        private void grdView_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            bool del = StaticUtil.GetBool(this.grdViewMatHang.GetRowCellValue(e.RowHandle, "DELE"));

            if (del)
            {
                e.Appearance.Font = MyStyle.DELETE_FONT;
                e.Appearance.ForeColor = MyStyle.DELETE_COLOR;
            }
        }

        private void grdViewMatHang_DoubleClick(object sender, EventArgs e)
        {
            UpdatePhieuNhap();
        }

        private void gridViewPhieuNhap_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            int PhieuNhapID = StaticUtil.GetInt(gridViewPhieuNhap.GetFocusedRowCellValue("PhieuNhapID"));
            this.PhieuNhapBO = Model.PhieuNhapBO.GetRootPhieuNhapBO(PhieuNhapID);
            this.PhieuNhapChiTietBOCollection = Model.PhieuNhapChiTietBOCollection.GetPhieuNhapChiTietBOCollection("PhieuNhapID = " + PhieuNhapID.ToString());

            lookUpEditNhaCungCap.EditValue = PhieuNhapBO.NhaCungCapID.Value;
            txtMaSo.Text = PhieuNhapBO.MaSo;
            txtNoidung.Text = PhieuNhapBO.NoiDung;
            txtGhichu.Text = PhieuNhapBO.GhiChu;
            dtNgayLapHoaDon.DateTime = PhieuNhapBO.NgayLapHoaDon.Value;

            spinEditVAT.Value = (decimal)PhieuNhapBO.MucVAT;
            spinEditChietKhau.Value = (decimal)PhieuNhapBO.MucChietKhau;
            spinEditPhucVu.Value = (decimal)PhieuNhapBO.MucPhucVu;
            spinEditGiamGia.Value = (decimal)PhieuNhapBO.MucGiamGia;
            spinEditTienPhatSinh.Value = (decimal)PhieuNhapBO.TienPhatSinh;
            txtLyDoPhatSinh.Text = PhieuNhapBO.LyDoPhatSinh;

            bdSourcePhieuNhapChiTiet.DataSource = PhieuNhapChiTietBOCollection.Clone();

            sapxep();
            TinhTien();
        }

        private void grdViewPhieuNhapChiTiet_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                int _idMatHang = StaticUtil.GetInt(this.grdViewPhieuNhapChiTiet.GetFocusedRowCellValue("MatHangID"));
                int _idDonViTinh = StaticUtil.GetInt(this.grdViewPhieuNhapChiTiet.GetFocusedRowCellValue("DonViTinhID"));
                double _soLuong = StaticUtil.GetDouble(this.grdViewPhieuNhapChiTiet.GetFocusedRowCellValue("SoLuong"));
                double _GiaMua = StaticUtil.GetDouble(this.grdViewPhieuNhapChiTiet.GetFocusedRowCellValue("DonGia"));

                int kiemtraID = this.PhieuNhapChiTietBOCollection.CheckExits(_idMatHang, _idDonViTinh);
                double thanhtien = (double)_soLuong * (double)_GiaMua;

                PhieuNhapChiTietBOCollection[kiemtraID].SoLuong = _soLuong;
                PhieuNhapChiTietBOCollection[kiemtraID].ThanhTien = thanhtien;
                sapxep();
                TinhTien();
            }
            catch { }
        }
        #endregion grid

        //=====================================
        #region function
        private void FilterMatHang()
        {
            Session.NhomHangID = StaticUtil.GetRealInt(this.grdView.GetFocusedRowCellValue("NhomHangID"));

            if (Session.NhomHangID == -1)
            {
                //this.grdViewPhieuNhapChiTiet.ActiveFilterString = "MatHangID=" + int.MaxValue;

                this.giaBOCollection = GiaBOCollection.GetGiaBOCollection();
                this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
            }
            else
            {
                MatHangBOCollection matHangBOCollection = MatHangBOCollection.GetMatHangBOCollection("NhomHangID = " + Session.NhomHangID.ToString());
                string strWhere = "";
                string listID = "";
                int recordCount = matHangBOCollection.Count;
                if (recordCount > 0)
                {
                    for (int i = 0; i < recordCount; i++)
                    {
                        object _idVattu = matHangBOCollection[i].MatHangID;
                        listID += _idVattu.ToString() + ",";
                    }
                }
                strWhere = strWhere + " MatHangID in ('" + listID.Replace(",", "','") + "')";
                this.giaBOCollection = GiaBOCollection.GetGiaBOCollection(strWhere);
                this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
            }

            //this.grdViewPhieuNhapChiTiet.ActiveFilterString = "MatHangID=" + int.MaxValue;


            //this.bdSourceGia.DataSource = this.MatHangBOCollection.Clone();

            //this.grdViewPhieuNhapChiTiet.CheckLoaded();
            //SetSttPhieuNhapChiTiet();
        }

        private void FilterMatHangByName(string nameMatHang)
        {
            //this.MatHangBOCollection = MatHangBOCollection.GetMatHangBOCollection("Ten like N'%" + nameMatHang + "%'");
            //this.bdSourceGia.DataSource = this.MatHangBOCollection.Clone();
            MatHangBOCollection matHangBOCollection = MatHangBOCollection.GetMatHangBOCollection(" Ten like N'%" + nameMatHang + "%' or MaMatHang like N'%" + nameMatHang + "%'");
            string strWhere = "";
            string listID = "";
            int recordCount = matHangBOCollection.Count;
            if (recordCount > 0)
            {
                for (int i = 0; i < recordCount; i++)
                {
                    object _idVattu = matHangBOCollection[i].MatHangID;
                    listID += _idVattu.ToString() + ",";
                }
            }
            strWhere = strWhere + " MatHangID in ('" + listID.Replace(",", "','") + "')";
            this.giaBOCollection = GiaBOCollection.GetGiaBOCollection(strWhere);
            this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
        }

        private void ResetData()
        {
            lookUpEditNhaCungCap.EditValue = null;
            lookUpMaKhachHang.EditValue = null;
            dtNgayLapHoaDon.DateTime = Session.NgayHeThong;
            txtMaSo.Text = "PN-" + Session.NgayHeThong.ToString("dd/MM/yyyy") + "-" + DateTime.Now.ToString("HH:mm:ss");
            txtGhichu.Text = "";
            txtNoidung.Text = "";
            txtLyDoPhatSinh.Text = "";
            spinEditChietKhau.Value = spinEditGiamGia.Value = spinEditPhucVu.Value = spinEditVAT.Value = spinEditTienPhatSinh.Value = 0;

            dtNgayLapHoaDon.DateTime = DateTime.Now;
            this.PhieuNhapBO = Model.PhieuNhapBO.NewRootPhieuNhapBO();
            this.PhieuNhapChiTietBOCollection = Model.PhieuNhapChiTietBOCollection.NewPhieuNhapChiTietBOCollection();
            sapxep();
            TinhTien();
            bdSourcePhieuNhapChiTiet.DataSource = this.PhieuNhapChiTietBOCollection.Clone();
        }

        private void RefreshData()
        {
            #region

            DanhMucBOList donViTinhBOList = DanhMucBOList.GetDanhMucBOList(LoaiDanhMuc.DonViTinh);
            Utility.SetData(this.reLookUpDonViTinh, donViTinhBOList, donViTinhBOList.Count);
            Utility.SetData(this.reLookUpDonViTinhID, donViTinhBOList, donViTinhBOList.Count);

            DanhMucBOList dmKhoBOList = DanhMucBOList.GetDanhMucBOList(LoaiDanhMuc.DanhMucKho);
            Utility.SetData(this.reLookUpDMKhoID, dmKhoBOList, dmKhoBOList.Count);

            MatHangBOList matHangBOList = MatHangBOList.GetMatHangBOList();
            Utility.SetData(this.reLookUpMatHang, matHangBOList, matHangBOList.Count);
            Utility.SetData(this.reLookUpMatHangID, matHangBOList, matHangBOList.Count);

            KhachHangBOList nhaccBOList = KhachHangBOList.GetKhachHangBOList("NCC = 1");
            Utility.SetData(this.reLookUpNhaCungCapID, nhaccBOList, nhaccBOList.Count);

            KhachHangBOCollection khachHangBOColl = KhachHangBOCollection.GetKhachHangBOCollection("NCC = 1");
            bdSourceNhaCungCap.DataSource = khachHangBOColl.Clone();

            #endregion BOList

            this.giaBOCollection = GiaBOCollection.GetGiaBOCollection();
            this.PhieuNhapBOCollection = Model.PhieuNhapBOCollection.GetPhieuNhapBOCollection(" (ThanhToan = 0 and TinhTrangThanhToan = 0 and TinhTrangXuatKho = 0 and (convert(nvarchar,NgayLapHoaDon,111) = '" + Session.NgayHeThong.ToString("yyyy/MM/dd") + "') and USRC = " + Session.LoginID.ToString() + ") or ( ThucHien = 1 " + " and USRC = " + Session.LoginID.ToString() + ")");
            this.nhomHangBOCollection = NhomHangBOCollection.GetNhomHangBOCollection();

            NhomHangBO NewNhomHangBO = NhomHangBO.NewRootNhomHangBO();
            NewNhomHangBO.Ten = "Tất cả";
            NewNhomHangBO.NhomHangID = -1;
            this.nhomHangBOCollection.Add(NewNhomHangBO);

            this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
            this.bdSourceNhomHang.DataSource = this.nhomHangBOCollection.Clone();
            this.bdSourcePhieuNhap.DataSource = this.PhieuNhapBOCollection.Clone();

            ResetData();

            FilterMatHang();
        }

        private void Edit()
        {
            this.formStatus = FormStatus.Edit;
            //SetFormStatus(this.formStatus);
            Session.CloseIndex++;
        }

        private void AddNew()
        {
            RefreshData();
        }

        private void Save()
        {
            if (kiemtraLuu() == 1)
            {
                this.PhieuNhapBO.NhaCungCapID = StaticUtil.GetInt(lookUpEditNhaCungCap.EditValue);
                this.PhieuNhapBO.MaSo = txtMaSo.Text.Trim();
                this.PhieuNhapBO.NgayLapHoaDon = dtNgayLapHoaDon.DateTime;
                this.PhieuNhapBO.NoiDung = txtNoidung.Text.Trim();
                this.PhieuNhapBO.GhiChu = txtGhichu.Text.Trim();

                this.PhieuNhapBO.MucVAT = StaticUtil.GetDouble(spinEditVAT.Value);
                this.PhieuNhapBO.MucChietKhau = StaticUtil.GetDouble(spinEditChietKhau.Value);
                this.PhieuNhapBO.MucPhucVu = StaticUtil.GetDouble(spinEditPhucVu.Value);
                this.PhieuNhapBO.MucGiamGia = StaticUtil.GetDouble(spinEditGiamGia.Value);
                this.PhieuNhapBO.TienPhatSinh = StaticUtil.GetDouble(spinEditTienPhatSinh.Value);
                this.PhieuNhapBO.LyDoPhatSinh = txtLyDoPhatSinh.Text.Trim();

                this.PhieuNhapBO.TongSo = StaticUtil.GetDouble(spinEditTongSo.Value);
                this.PhieuNhapBO.ThanhTien = StaticUtil.GetDouble(spinEditThanhTien.Value);
                this.PhieuNhapBO.TienPhaiTra = StaticUtil.GetDouble(spinEditTongTien.Value);
                this.PhieuNhapBO.TienTra = 0;
                this.PhieuNhapBO.BangChu = txtBangChu.Text.Trim();
                this.PhieuNhapBO.TienThieu = this.PhieuNhapBO.TienTra.Value - this.PhieuNhapBO.TienPhaiTra.Value;
                this.PhieuNhapBO.ThanhToan = 0;
                this.PhieuNhapBO.TinhTrangXuatKho = 0;
                this.PhieuNhapBO.TinhTrangThanhToan = 0;

                if (StaticUtil.GetInt(this.PhieuNhapBO.ThucHien, 0) != 1)
                    this.PhieuNhapBO.ThucHien = 0;
                else
                    this.PhieuNhapBO.ThucHien = 1;
                this.PhieuNhapBO.Save();

                int recordCount = this.PhieuNhapChiTietBOCollection.Count;
                if (recordCount > 0)
                {
                    for (int i = 0; i < recordCount; i++)
                    {
                        this.PhieuNhapChiTietBOCollection[i].PhieuNhapID = this.PhieuNhapBO.PhieuNhapID.Value;
                    }

                    this.PhieuNhapChiTietBOCollection.Save();
                }
                this.PhieuNhapChiTietBOCollection = this.PhieuNhapChiTietBOCollection.Save();

                MessageBox.Show("Cập nhật thành công! ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.PhieuNhapBOCollection = Model.PhieuNhapBOCollection.GetPhieuNhapBOCollection(" (ThanhToan = 0 and TinhTrangThanhToan = 0 and TinhTrangXuatKho = 0 and (convert(nvarchar,NgayLapHoaDon,111) = '" + Session.NgayHeThong.ToString("yyyy/MM/dd") + "') and USRC = " + Session.LoginID.ToString() + ") or ( ThucHien = 1 " + " and USRC = " + Session.LoginID.ToString() + ")");
                this.bdSourcePhieuNhap.DataSource = this.PhieuNhapBOCollection.Clone();

            }


            FilterMatHang();
        }

        private void Cancel()
        {
            this.formStatus = FormStatus.View;
            //SetFormStatus(this.formStatus);
            Session.CloseIndex--;

            this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
            this.bdSourcePhieuNhapChiTiet.DataSource = this.PhieuNhapChiTietBOCollection.Clone();

            FilterMatHang();
        }

        private void UpdatePhieuNhap()
        {
            int matHangID = StaticUtil.GetInt(grdViewMatHang.GetFocusedRowCellValue("MatHangID"));
            int donViTinhID = StaticUtil.GetInt(grdViewMatHang.GetFocusedRowCellValue("DonViTinhID"));
            double GiaMua = StaticUtil.GetDouble(grdViewMatHang.GetFocusedRowCellValue("GiaMua"), 0);
            int kiemtraID = this.PhieuNhapChiTietBOCollection.CheckExits(matHangID, donViTinhID);
            if (kiemtraID == -1)
            {
                PhieuNhapChiTietBO newBO = PhieuNhapChiTietBO.NewRootPhieuNhapChiTietBO();
                newBO.MatHangID = matHangID;
                newBO.TenHang = MatHangBO.GetRootMatHangBO(matHangID).Ten;
                newBO.MaVach = "0";
                newBO.DonViTinhID = donViTinhID;
                newBO.TenDonViTinh = DanhMucBO.GetRootDanhMucBO(donViTinhID).NoiDung;
                newBO.DonGia = GiaMua;
                newBO.SoLuong = 1;
                newBO.ThanhTien = GiaMua * newBO.SoLuong.Value;
                PhieuNhapChiTietBOCollection.Add(newBO);

                sapxep();
                TinhTien();
            }
            else
                MessageBox.Show("Mặt hàng và Đơn vị tính này đã có! ", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }

        private void sapxep()
        {

            int length = PhieuNhapChiTietBOCollection.Count;

            for (int i = 0; i < length; i++)
            {
                PhieuNhapChiTietBOCollection[i].STT0 = (i + 1);
            }

            bdSourcePhieuNhapChiTiet.DataSource = PhieuNhapChiTietBOCollection;
        }

        private void TinhTien()
        {
            double tongso = 0;
            double thanhtien = 0;
            double tongtien = 0;

            int length = PhieuNhapChiTietBOCollection.Count;

            for (int i = 0; i < length; i++)
            {
                tongso = tongso + StaticUtil.GetDouble(PhieuNhapChiTietBOCollection[i].SoLuong, 0);
                thanhtien = thanhtien + StaticUtil.GetDouble(PhieuNhapChiTietBOCollection[i].ThanhTien, 0);
            }

            spinEditTongSo.Value = (decimal)tongso;
            spinEditThanhTien.Value = (decimal)thanhtien;

            double mucVAT = StaticUtil.GetDouble(spinEditVAT.Value, 0);
            double tienVAT = thanhtien * mucVAT;
            spinEditTienVAT.Value = (decimal)tienVAT;
            double mucCK = StaticUtil.GetDouble(spinEditChietKhau.Value, 0);
            double tienCK = thanhtien * mucCK;
            spinEditTienChietKhau.Value = (decimal)tienCK;
            double mucGG = StaticUtil.GetDouble(spinEditGiamGia.Value, 0);
            double tienGG = thanhtien * mucGG;
            spinEditTienGiamGia.Value = (decimal)tienGG;
            double mucPV = StaticUtil.GetDouble(spinEditPhucVu.Value, 0);
            double tienPV = thanhtien * mucPV;
            spinEditTienPhucVu.Value = (decimal)tienPV;
            double TienPhatSinh = StaticUtil.GetDouble(spinEditTienPhatSinh.Value, 0);

            tongtien = thanhtien + tienVAT + TienPhatSinh + tienCK - tienGG + tienPV;
            spinEditTongTien.Value = (decimal)tongtien;
            txtBangChu.Text = VNCurrency.ToString(tongtien);
        }

        private void DeleteMatHang(int mathangID, int donvitinhID)
        {

            if (MessageBox.Show("Bạn có muốn xóa Mặt Hàng và Đơn vị tính này không? ", "Cảnh báo!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                int _idPhieuNhap = StaticUtil.GetInt(this.grdViewPhieuNhapChiTiet.GetFocusedRowCellValue("PhieuNhapChiTietID"), -1);

                if (_idPhieuNhap >= 0)
                {
                    PhieuNhapChiTietBO.DeletePhieuNhapChiTietBO(_idPhieuNhap);
                }
                //PhieuNhapChiTietBOCollection.Remove(mathangID,donvitinhID);
                sapxep();
            }
        }

        private int kiemtraLuu()
        {
            int tempkiemtra = 1;
            string strError = "";

            if (lookUpEditNhaCungCap.EditValue == null)
            {
                tempkiemtra = 0;
                strError = "Chưa chọn Khách hàng";
            }

            if (txtMaSo.Text.Trim() == "")
            {
                tempkiemtra = 0;
                strError = strError + " ;Chưa nhập Mã số";
            }

            if (tempkiemtra == 0)
                MessageBox.Show(strError, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return tempkiemtra;
        }



        #endregion function

        private void toolStripMenuItemNhapKho_Click(object sender, EventArgs e)
        {
            int _PhieuNhapID = StaticUtil.GetInt(this.PhieuNhapBO.PhieuNhapID, -1);
            if (_PhieuNhapID >= 0 && this.PhieuNhapBO != null)
            {
                FrmNhapKho2 frmNhapKho2 = new FrmNhapKho2((FrmMain)this.ParentForm, 0, this.PhieuNhapBO, this.PhieuNhapChiTietBOCollection);
                frmNhapKho2.OnCompleted += new OnCompletedEventHandler(frmNhapKho2_OnCompleted);
                frmNhapKho2.Show();
            }
            else
                MessageBox.Show("Chưa chọn Hóa đơn Bán hàng để Thu tiền! ", "Thông báo", MessageBoxButtons.OK);
        }

        private void frmNhapKho2_OnCompleted(object sender, OnCompletedEventArgs e)
        {
            int daluu = (int)e.objectValue;
            if (daluu == 1)
                RefreshData();

            this.BringToFront();
        }

        private void txtTimkiem_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyData == Keys.Enter)
            {
                grdViewMatHang.Focus();
            }
        }

        private void grdViewMatHang_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyData == Keys.Enter)
            {
                UpdatePhieuNhap();
            }
        }
    }
}